package cn.wolfcode.wolf2w.service.impl;

import cn.wolfcode.wolf2w.domain.UserInfo;
import cn.wolfcode.wolf2w.exception.LogicException;
import cn.wolfcode.wolf2w.redis.service.IUserInfoRedisService;
import cn.wolfcode.wolf2w.repository.UserInfoRepository;
import cn.wolfcode.wolf2w.service.IUserInfoService;

import cn.wolfcode.wolf2w.util.AssertUtil;
import cn.wolfcode.wolf2w.util.Consts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;


import java.util.List;
import java.util.UUID;


@Service
//@Transactional mongodb事务必须复制集方式
public class UserInfoServiceImpl implements IUserInfoService {

    //service在core项目中, 配置位置是api项目, 后续mgrsite也会用到core项目
    //那么如果在这个地方注入配置属性,后续必须在mgrsite配置文件中添加2个配置
   // sms.url   sms.appkey
   /* @Value("${sms.url}")
    private String smsUrl;
    @Value("${sms.appkey}")
    private String appKey;*/


    @Autowired
    private IUserInfoRedisService userInfoRedisService;

    @Autowired
    private UserInfoRepository repository;

//    @Autowired
//    private IUserInfoRedisService userInfoRedisService;
    @Override
    public void save(UserInfo userInfo) {
        userInfo.setId(null);
        repository.save(userInfo);
    }

    @Override
    public void update(UserInfo userInfo) {
        repository.save(userInfo);
    }

    @Override
    public void delete(String id) {
        repository.deleteById(id);
    }

    @Override
    public UserInfo get(String id) {
        return repository.findById(id).orElse(null);
    }

    @Override
    public List<UserInfo> list() {
        return repository.findAll();
    }

    @Override
    public boolean checkPhone(String phone) {

        UserInfo userInfo = repository.findByPhone(phone);

        return userInfo != null;
    }

    @Override
    public void sendVerifyCode(String phone) {

        //1:创建验证码, 编辑短信
        String code = UUID.randomUUID().toString().
                replaceAll("-", "").substring(0, 4);
        //创建短信
        StringBuilder sb = new StringBuilder(80);
        sb.append("您注册验证码:").append(code).append(", 请您在").
                append(Consts.VERIFY_CODE_VAI_TIME).append("分钟之内使用");

        //假装短信发送成功
        System.out.println(sb);


        //真实发短信本质就是java发起httpp请求
       // springMvc提供一个工具栏
       // spring提供http请求发送类

        /*RestTemplate restTemplate = new RestTemplate();
        //参数1: 请求url[url中有参数占位符], 参数2:返回值类型, 参数3:请求需要参数
        String url = "Url:https://way.jd.com/chonry/sms?sign=【创瑞云】&mobile={1}&content={2}&appkey={3}";

        String ret = restTemplate.getForObject(url, String.class,phone,sb.toString(), "2458f08fcee20a8fe956554e4f0c0e62");
        System.out.println(ret);
        //contains
        if(!ret.contains("Success")){
        throw new LogicException("短信发送失败");
        }
*/

        //3:将验证码缓存到redis中Re's't'template
        userInfoRedisService.setVerifyCode(phone, code);

    }

    @Override
    public void regist(String phone, String nickname, String password, String rpassword, String verifyCode) {
        //判断传入参数是否为null
        AssertUtil.hasLength(phone, "手机号码不能为空");
        AssertUtil.hasLength(nickname, "昵称不能为空");
        AssertUtil.hasLength(password, "密码不能为空");
        AssertUtil.hasLength(rpassword, "确认密码不能为空");
        AssertUtil.hasLength(verifyCode, "验证码不能为空");
        //判断2次输入的密码是否一致
        AssertUtil.isEquals(password, rpassword, "两次输入密码不一致");
        //判断手机号码是否符合格式 @TODO
        //判断手机号是否唯一
        if(this.checkPhone(phone)){
            throw new LogicException("该手机号码已经被注册了");
        }
        //判断验证是否正确
        String code = userInfoRedisService.getVerifyCode(phone);
        if(code == null || !code.equalsIgnoreCase(verifyCode)){
            throw new LogicException("验证码失效或错误");
        }
        //注册
        UserInfo userInfo = new UserInfo();
        userInfo.setNickname(nickname);
        userInfo.setPhone(phone);
        userInfo.setEmail("");
        userInfo.setPassword(password); //假装加密
        userInfo.setLevel(1);
        userInfo.setCity("");
        userInfo.setHeadImgUrl("/images/default.jpg");
        userInfo.setInfo("");
        //关键字段建议大家自己控制
        userInfo.setState(UserInfo.STATE_NORMAL);

        /*throw new  RuntimeException("恶心系统异常kldjfkjsdkjfksdjfkjskfksj" +
                "dklfjksldjfksdjkfjskdjfksdjfkjsdkfjsdkljsdfkjsdkfjksdjfksd");*/


        this.save(userInfo);
    }
    //只负责登入检查（一个方法只做一件事情）
    @Override
    public UserInfo login(String username, String password) {
        //1: password之前加密, 此处需要加密
        //2: 此处需要进行参数为null判断
        UserInfo user = repository.findByPhone(username);
//LogicException自定义的异常
        if(user == null || !password.equals(user.getPassword())){
            throw new LogicException("账号或密码错误");
        }
        user.setPassword("");//不让密码显示在控制台
        return user;
    }
    @Override
    public List<UserInfo> queryCity(String city) {
        return repository.findByCity(city);
    }


}
